<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Android中图片是以Bitmap形式存在的，Bitmap所占内存直接影响应用所占内存大小，Bitmap所占内存大小计算公式:图片长度  图片宽度  一个像素点占用的字节数 Bitmap压缩颜色格式:">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Android-图像压缩">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Android/Android-图像压缩/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="Android中图片是以Bitmap形式存在的，Bitmap所占内存直接影响应用所占内存大小，Bitmap所占内存大小计算公式:图片长度  图片宽度  一个像素点占用的字节数 Bitmap压缩颜色格式:">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-cba206790c688941?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T11:22:49.324Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android-图像压缩">
<meta name="twitter:description" content="Android中图片是以Bitmap形式存在的，Bitmap所占内存直接影响应用所占内存大小，Bitmap所占内存大小计算公式:图片长度  图片宽度  一个像素点占用的字节数 Bitmap压缩颜色格式:">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/3110861-cba206790c688941?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Android/Android-图像压缩/"/>





  <title>Android-图像压缩 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Android/Android-图像压缩/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android-图像压缩</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Android中图片是以Bitmap形式存在的，Bitmap所占内存直接影响应用所占内存大小，Bitmap所占内存大小计算公式:<br>图片长度 <em> 图片宽度 </em> 一个像素点占用的字节数</p>
<p>Bitmap压缩颜色格式:<br><img src="http://upload-images.jianshu.io/upload_images/3110861-cba206790c688941?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<a id="more"></a>
<ol>
<li>质量压缩<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Bitmap bitmap = BitmapFactory.decodeFile(path);</span><br><span class="line">ByteArrayOutputStream baos = new ByteArrayOutputStream();</span><br><span class="line">int quality = 80;</span><br><span class="line">bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);</span><br><span class="line">byte[] bytes = baos.toByteArray();</span><br><span class="line">bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>图片的大小没有变化，因为质量有压缩不会减少图片的像素，它是在保持像素的前提下改变图图片的位深及透明度，来达到压缩图片的目的。<br><strong>注: 当compress方法中第一个参数为Bitmap.CompressFormat.PNG时，quality没有作用，因为png图片时无损的，不能进行压缩。</strong></p>
<ol start="2">
<li>采样率压缩<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BitmapFactory.Options options = new BitmapFactory.Options();</span><br><span class="line">options.inSampleSize = 2;</span><br><span class="line">Bitmap bitmap = BitmapFactory.decodeFile(path, options);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>设置inSampleSize的值为2时，宽和高都变为原来的1/2。</p>
<p><strong>注：当设置options.inJustDecodeBounds = true时，BitmapFactory解码图片时会返回空的Bitmap对象，但是也可以返回Bitmap的宽、高以及MimeType。</strong></p>
<ol start="3">
<li>缩放法压缩(Martix)<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Matrix matrix = new Matrix();</span><br><span class="line">matrix.setScale(0.5f, 0.5f);</span><br><span class="line">Bitmap bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),</span><br><span class="line">    bitmap.getHeight(), matrix, true);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>其中，bitmap的宽高分别缩小了一半，图片大小压缩成1/4。</p>
<ol start="4">
<li>RGB_565<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BitmapFactory.Options options = new BitmapFactory.Options();</span><br><span class="line">options.inPreferredConfig = Bitmap.Config.RGB_565;</span><br><span class="line">Bitmap bitmap = BitmapFactory.decodeFile(path, options);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>图片大小直接缩小了一半，宽高没有变。<br><strong>注意：由于ARGB_4444的画质惨不忍睹，一般假如对图片没有透明度要求的话，可以改成RGB_565，相比ARGB_8888将节省一半的内存开销。</strong></p>
<ol start="5">
<li>createScaledBitmap<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Bitmap bitmap = BitmapFactory.decodeFile(path);</span><br><span class="line">bitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>这里将图片压缩成用户所期望的宽高。</p>
<p><strong>系统压缩工具类</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">从Android 2.2开始系统新增了一个缩略图ThumbnailUtils类，位于framework包下的android.media.ThumbnailUtils位置，可以帮助我们从mediaprovider中获取系统中的视频或图片文件的缩略图，该类提供了三种静态方法可以直接调用获取。</span><br><span class="line"> 1、extractThumbnail (source, width, height)：</span><br><span class="line"> /**</span><br><span class="line">  * 创建一个指定大小的缩略图</span><br><span class="line">  * @param source 源文件(Bitmap类型)</span><br><span class="line">  * @param width  压缩成的宽度</span><br><span class="line">  * @param height 压缩成的高度</span><br><span class="line">  */</span><br><span class="line">  ThumbnailUtils.extractThumbnail(source, width, height);  </span><br><span class="line"></span><br><span class="line">2、extractThumbnail(source, width, height, options):</span><br><span class="line">/**</span><br><span class="line">  * 创建一个指定大小居中的缩略图</span><br><span class="line">  * @param source 源文件(Bitmap类型)</span><br><span class="line">  * @param width  输出缩略图的宽度</span><br><span class="line">  * @param height 输出缩略图的高度</span><br><span class="line">  * @param options 如果options定义为OPTIONS_RECYCLE_INPUT,则回收@param source这个资源文件</span><br><span class="line">  * (除非缩略图等于@param source)</span><br><span class="line">  *</span><br><span class="line">  */</span><br><span class="line">ThumbnailUtils.extractThumbnail(source, width, height, options);  </span><br><span class="line"></span><br><span class="line">3、createVideoThumbnail(filePath, kind): </span><br><span class="line">/**</span><br><span class="line">  * 创建一张视频的缩略图</span><br><span class="line">  * 如果视频已损坏或者格式不支持可能返回null</span><br><span class="line">  * @param filePath 视频文件路径  如：/sdcard/android.3gp</span><br><span class="line">  * @param kind kind可以为MINI_KIND或MICRO_KIND</span><br><span class="line">  *</span><br><span class="line">  */</span><br><span class="line"> ThumbnailUtils.createVideoThumbnail(filePath, kind);</span><br></pre></td></tr></table></figure></p>
<p><strong>压缩工具类</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br></pre></td><td class="code"><pre><span class="line">public class CompressUtils &#123;  </span><br><span class="line">    /** </span><br><span class="line">     * 按质量压缩 </span><br><span class="line">     * @param bitmap </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">        public static Bitmap compressImage(Bitmap bitmap)&#123;  </span><br><span class="line">            ByteArrayOutputStream baos = new ByteArrayOutputStream();  </span><br><span class="line">            //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  </span><br><span class="line">            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  </span><br><span class="line">            int options = 100;  </span><br><span class="line">            //循环判断如果压缩后图片是否大于100kb,大于继续压缩  </span><br><span class="line">            while ( baos.toByteArray().length / 1024&gt;100) &#123;  </span><br><span class="line">                //清空baos  </span><br><span class="line">                baos.reset();  </span><br><span class="line">                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);  </span><br><span class="line">                options -= 10;//每次都减少10  </span><br><span class="line">            &#125;  </span><br><span class="line">            //把压缩后的数据baos存放到ByteArrayInputStream中  </span><br><span class="line">            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());  </span><br><span class="line">            //把ByteArrayInputStream数据生成图片  </span><br><span class="line">            Bitmap newBitmap = BitmapFactory.decodeStream(isBm, null, null);  </span><br><span class="line">            return newBitmap;  </span><br><span class="line">        &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * 按图片尺寸压缩 参数为路径 </span><br><span class="line">     * @param imgPath 图片路径 </span><br><span class="line">     * @param pixelW 目标图片宽度 </span><br><span class="line">     * @param pixelH 目标图片高度 </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static Bitmap compressImageFromPath(String imgPath, int pixelW, int pixelH) &#123;  </span><br><span class="line">        BitmapFactory.Options options = new BitmapFactory.Options();  </span><br><span class="line">        // 开始读入图片，此时把options.inJustDecodeBounds 设回true，即只读边不读内容  </span><br><span class="line">        options.inJustDecodeBounds = true;  </span><br><span class="line">        options.inPreferredConfig = Bitmap.Config.RGB_565;  </span><br><span class="line">        BitmapFactory.decodeFile(imgPath,options);  </span><br><span class="line">        options.inJustDecodeBounds = false;  </span><br><span class="line">        options.inSampleSize = computeSampleSize(options , pixelH &gt; pixelW ? pixelH : pixelW ,pixelW * pixelH );  </span><br><span class="line">        Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);  </span><br><span class="line">        return bitmap;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * 按图片尺寸压缩 参数是bitmap </span><br><span class="line">     * @param bitmap </span><br><span class="line">     * @param pixelW </span><br><span class="line">     * @param pixelH </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static Bitmap compressImageFromBitmap(Bitmap bitmap, int pixelW, int pixelH) &#123;  </span><br><span class="line">        ByteArrayOutputStream os = new ByteArrayOutputStream();  </span><br><span class="line">        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);  </span><br><span class="line">        if( os.toByteArray().length / 1024&gt;1024) &#123;//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出  </span><br><span class="line">            os.reset();  </span><br><span class="line">            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%，把压缩后的数据存放到baos中  </span><br><span class="line">        &#125;  </span><br><span class="line">        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());  </span><br><span class="line">        BitmapFactory.Options options = new BitmapFactory.Options();  </span><br><span class="line">        options.inJustDecodeBounds = true;  </span><br><span class="line">        options.inPreferredConfig = Bitmap.Config.RGB_565;  </span><br><span class="line">        BitmapFactory.decodeStream(is, null, options);  </span><br><span class="line">        options.inJustDecodeBounds = false;  </span><br><span class="line">        options.inSampleSize = computeSampleSize(options , pixelH &gt; pixelW ? pixelH : pixelW ,pixelW * pixelH );  </span><br><span class="line">        is = new ByteArrayInputStream(os.toByteArray());  </span><br><span class="line">        Bitmap newBitmap = BitmapFactory.decodeStream(is, null, options);  </span><br><span class="line">        return newBitmap;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * 对图片进行缩放指定大小 </span><br><span class="line">     * @param bitmap </span><br><span class="line">     * @param width </span><br><span class="line">     * @param height </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static Bitmap scaleTo(Bitmap bitmap, int width, int height)&#123;  </span><br><span class="line">        int originalWidth = bitmap.getWidth();  </span><br><span class="line">        int originalHeight = bitmap.getHeight();  </span><br><span class="line">        float xScale = (float)width / originalWidth;  </span><br><span class="line">        float yScale = (float)height / originalHeight;  </span><br><span class="line">        Matrix matrix = new Matrix();  </span><br><span class="line">        matrix.setScale(xScale,yScale);  </span><br><span class="line">        return Bitmap.createBitmap(bitmap, 0, 0, originalWidth, originalHeight, matrix, true);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * 以最省内存的方式读取本地资源的图片 </span><br><span class="line">     * @param context </span><br><span class="line">     * @param resId </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static Bitmap readBitmap(Context context, int resId) &#123;  </span><br><span class="line">        BitmapFactory.Options opt = new BitmapFactory.Options();  </span><br><span class="line">        opt.inPreferredConfig = Bitmap.Config.RGB_565;  </span><br><span class="line">        opt.inPurgeable = true;  </span><br><span class="line">        opt.inInputShareable = true;  </span><br><span class="line">        // 获取资源图片  </span><br><span class="line">        InputStream is = context.getResources().openRawResource(resId);  </span><br><span class="line">        return BitmapFactory.decodeStream(is, null, opt);  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    /** </span><br><span class="line">     * android源码提供给我们的动态计算出图片的inSampleSize方法 </span><br><span class="line">     * @param options </span><br><span class="line">     * @param minSideLength </span><br><span class="line">     * @param maxNumOfPixels </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) &#123;  </span><br><span class="line">        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);  </span><br><span class="line">        int roundedSize;  </span><br><span class="line">        if (initialSize &lt;= 8) &#123;  </span><br><span class="line">            roundedSize = 1;  </span><br><span class="line">            while (roundedSize &lt; initialSize) &#123;  </span><br><span class="line">                roundedSize &lt;&lt;= 1;  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125; else &#123;  </span><br><span class="line">            roundedSize = (initialSize + 7) / 8 * 8;  </span><br><span class="line">        &#125;  </span><br><span class="line">        return roundedSize;  </span><br><span class="line">    &#125;  </span><br><span class="line">  </span><br><span class="line">    private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) &#123;  </span><br><span class="line">        double w = options.outWidth;  </span><br><span class="line">        double h = options.outHeight;  </span><br><span class="line">        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  </span><br><span class="line">        int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));  </span><br><span class="line">        if (upperBound &lt; lowerBound) &#123;  </span><br><span class="line">            return lowerBound;  </span><br><span class="line">        &#125;  </span><br><span class="line">        if ((maxNumOfPixels == -1) &amp;&amp; (minSideLength == -1)) &#123;  </span><br><span class="line">            return 1;  </span><br><span class="line">        &#125; else if (minSideLength == -1) &#123;  </span><br><span class="line">            return lowerBound;  </span><br><span class="line">        &#125; else &#123;  </span><br><span class="line">            return upperBound;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>有效的处理Bitmap OOM方法</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line">public class BitmapActivity extends Activity &#123;  </span><br><span class="line">    public ImageView imageView = null;  </span><br><span class="line">    @Override  </span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;  </span><br><span class="line">        super.onCreate(savedInstanceState);  </span><br><span class="line">        setContentView(R.layout.bitmap_activity);  </span><br><span class="line">        imageView = (ImageView) findViewById(R.id.imageView1);  </span><br><span class="line">        ImageAsyncTask task = new ImageAsyncTask(imageView,50,50);  </span><br><span class="line">        task.execute(&quot;http://image.baidu.com/search/down?tn=download&amp;word=download&amp;ie=utf8&amp;fr=detail&amp;url=http%3A%2F%2Fimg1.pconline.com.cn%2Fpiclib%2F200904%2F28%2Fbatch%2F1%2F32910%2F12408824046039mk21hbi75.jpg&amp;thumburl=http%3A%2F%2Fimg2.imgtn.bdimg.com%2Fit%2Fu%3D3414739956%2C4196877666%26fm%3D21%26gp%3D0.jpg&quot;);  </span><br><span class="line">    &#125;  </span><br><span class="line">    /** </span><br><span class="line">     * 计算出压缩比 </span><br><span class="line">     * @param options </span><br><span class="line">     * @param reqWith </span><br><span class="line">     * @param reqHeight </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight)  </span><br><span class="line">    &#123;  </span><br><span class="line">        //通过参数options来获取真实图片的宽、高  </span><br><span class="line">        int width = options.outWidth;  </span><br><span class="line">        int height = options.outHeight;  </span><br><span class="line">        int inSampleSize = 1;//初始值是没有压缩的  </span><br><span class="line">        if(width &gt; reqWidth || height &gt; reqHeight)  </span><br><span class="line">        &#123;  </span><br><span class="line">            //计算出原始宽与现有宽，原始高与现有高的比率  </span><br><span class="line">            int widthRatio = Math.round((float)width/(float)reqWidth);  </span><br><span class="line">            int heightRatio = Math.round((float)height/(float)reqHeight);  </span><br><span class="line">            //选出两个比率中的较小值，这样的话能够保证图片显示完全   </span><br><span class="line">            inSampleSize = widthRatio &lt; heightRatio ? widthRatio:heightRatio;  </span><br><span class="line">        &#125;  </span><br><span class="line">        System.out.println(&quot;压缩比:  &quot;+inSampleSize);  </span><br><span class="line">        return inSampleSize;  </span><br><span class="line">    &#125;  </span><br><span class="line">    /** </span><br><span class="line">     * 将InputStream转换为Byte数组 </span><br><span class="line">     * @param in </span><br><span class="line">     * @return </span><br><span class="line">     */  </span><br><span class="line">    public static byte[] inputStreamToByteArray(InputStream in)  </span><br><span class="line">    &#123;  </span><br><span class="line">        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  </span><br><span class="line">        byte[] buffer = new byte[1024];  </span><br><span class="line">        int len;  </span><br><span class="line">        try &#123;  </span><br><span class="line">            while((len = in.read(buffer)) != -1)  </span><br><span class="line">            &#123;  </span><br><span class="line">                outputStream.write(buffer, 0, len);  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125; catch (IOException e) &#123;  </span><br><span class="line">            e.printStackTrace();  </span><br><span class="line">        &#125;finally&#123;  </span><br><span class="line">            try &#123;  </span><br><span class="line">                in.close();  </span><br><span class="line">                outputStream.close();  </span><br><span class="line">            &#125; catch (IOException e) &#123;  </span><br><span class="line">                e.printStackTrace();  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">        return outputStream.toByteArray();  </span><br><span class="line">    &#125;  </span><br><span class="line">      </span><br><span class="line">    class ImageAsyncTask extends AsyncTask&lt;String, Void, Bitmap&gt;  </span><br><span class="line">    &#123;  </span><br><span class="line">        public ImageView iv;  </span><br><span class="line">        public int reqWidth;  </span><br><span class="line">        public int reqHeight;  </span><br><span class="line">        public ImageAsyncTask(ImageView imageView,int reqWidth,int reqHeight)  </span><br><span class="line">        &#123;  </span><br><span class="line">            this.iv = imageView;  </span><br><span class="line">            this.reqWidth = reqWidth;  </span><br><span class="line">            this.reqHeight = reqHeight;  </span><br><span class="line">        &#125;  </span><br><span class="line">        @Override  </span><br><span class="line">        protected Bitmap doInBackground(String... params) &#123;  </span><br><span class="line">            URL url;  </span><br><span class="line">            HttpURLConnection connection = null;  </span><br><span class="line">            InputStream in = null;  </span><br><span class="line">            Bitmap beforeBitmap = null;  </span><br><span class="line">            Bitmap afterBitmap = null;  </span><br><span class="line">            try &#123;  </span><br><span class="line">                url = new URL(params[0]);  </span><br><span class="line">                connection = (HttpURLConnection) url.openConnection();  </span><br><span class="line">                in = connection.getInputStream();  </span><br><span class="line">                BitmapFactory.Options options = new BitmapFactory.Options();  </span><br><span class="line">                //设置BitmapFactory.Options的inJustDecodeBounds属性为true表示禁止为bitmap分配内存  </span><br><span class="line">                options.inJustDecodeBounds = true;  </span><br><span class="line">                byte[] data = inputStreamToByteArray(in);  </span><br><span class="line">                beforeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);//这次调用的目的是获取到原始图片的宽、高，但是这次操作是没有写内存操作的  </span><br><span class="line">                options.inSampleSize = calculateInSampleSize(options,reqWidth, reqHeight);   </span><br><span class="line">                //设置这次加载图片需要加载到内存中  </span><br><span class="line">                options.inJustDecodeBounds = false;  </span><br><span class="line">                afterBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);  </span><br><span class="line">                float afterSize = (float)(afterBitmap.getRowBytes()*afterBitmap.getHeight());  </span><br><span class="line">                System.out.println(&quot;压缩之后的图片大小:  &quot;+(float)afterSize/1024+&quot;KB&quot;);  </span><br><span class="line">            &#125; catch (Exception e) &#123;  </span><br><span class="line">                System.out.println(e.toString());  </span><br><span class="line">            &#125;  </span><br><span class="line">            return afterBitmap;  </span><br><span class="line">        &#125;  </span><br><span class="line">          </span><br><span class="line">        @Override  </span><br><span class="line">        protected void onPostExecute(Bitmap result) &#123;  </span><br><span class="line">            if(result != null)  </span><br><span class="line">                imageView.setImageBitmap(result);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Android/Android-命令行获取apk信息/" rel="next" title="Android-命令行获取apk信息">
                <i class="fa fa-chevron-left"></i> Android-命令行获取apk信息
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Android/Android-文件路径/" rel="prev" title="Android-文件路径">
                Android-文件路径 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
